package com.bingkaimedia.merchantbeta.app;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bingkaimedia.merchantbeta.R;
import com.bingkaimedia.merchantbeta.libs.JSONfunctions;
import com.bingkaimedia.merchantbeta.libs.LazyAdapter;
import com.bingkaimedia.merchantbeta.libs.SessionManager;
import com.bingkaimedia.merchantbeta.libs_image.ImageLoader;
import com.bingkaimedia.merchantbeta.libs_slidemenu.BaseActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
  
   
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

@SuppressLint("NewApi")
public class Search  extends BaseActivity   {
	
	int current_page = 0;
	
	
	
	// XML node keys 
	//static final String KEY_SONG = "song"; // parent node
	public static final String KEY_VOUCHER_ID = "voucher_id";
	public static final String KEY_VOUCHER_NAME = "voucher_name"; 
	public static final String KEY_VOUCHER_TOTAL = "voucher_total";
	public static final String KEY_VOUCHER_TERSEDIA = "voucher_tersedia";
	public static final String KEY_VOUCHER_DETAIL = "voucher_detail";
	public static final String KEY_VOUCHER_DATE = "voucher_date";
	public static final String KEY_VOUCHER_DESCRIPTION = "voucher_description";
	public static final String KEY_MERCHANT_ID = "merchant_id";
	public static final String KEY_MERCHANT_NAME = "merchant_name";
	public static final String KEY_MERCHANT_CATEGORY = "voucher_category";
	public static final String KEY_MERCHANT_PHOTO = "merchant_photo";
	public static final String KEY_TRANSACTION_ID = "transaction_id";
	public static final String KEY_TRANSACTION_DATE = "transaction_date";
	public static final String KEY_TRANSACTION_IMAGE = "transaction_image";
	public static final String KEY_TRANSACTION_STATUS = "transaction_status";
	
	public static final String KEY_MY_CHANNEL_ID = "my_channel_id";
	public static final String KEY_CHANNEL_ID = "channel_id";
	public static final String KEY_USERS_ID = "users_id";
	public static final String KEY_CHANNEL_NAME = "channel_name";
	public static final String KEY_CHANNEL_ADDRESS = "channel_address";
	public static final String KEY_CHANNEL_PHOTO = "channel_photo";
	public static final String KEY_CHANNEL_NOTE = "channel_note";
	
	
	public static final String KEY_CATEGORY = "voucher_category";  
	public static final String KEY_CATEGORY_ID = "id_voucher_category";  
	
	private String xml_programs_cat; 
	private String xml_programs_cat_id; 
	
	public static final String KEY_city_ID = "id_cities";  
	public static final String KEY_city_CODE = "id_countries";  
	public static final String KEY_city_NAME = "City";  
	public static final String KEY_city_PHONE = "Region";

	private ArrayList<Category_Array> categorylist;
	List<String> lables = new ArrayList<String>();
	
	private String xml_city_id;
	private String xml_city_code;
	private String xml_city_name;
	private String xml_city_phone;
	 
	
	private String xml_voucher_id;
	private String xml_voucher_name;
	private String xml_voucher_total;
	private String xml_voucher_tersedia;
	private String xml_voucher_description;
	private String xml_voucher_detail;
	private String xml_voucher_date;
	private String xml_merchant_id;
	private String xml_merchant_name;
	private String xml_merchant_category;
	private String xml_merchant_photo;
	private String xml_transaction_id;
	private String xml_transaction_date;
	private String xml_transaction_image;
	private String xml_transaction_status;
	

	private String xml_my_channel_id;
	private String xml_channel_id;
	private String xml_users_id;
	private String xml_channel_name;
	private String xml_channel_photo;
	private String xml_channel_note;
	private String xml_channel_address;

	private static String session_userid;
	private static String session_username;
	private static String session_password;
	private static String session_email;
	private static String session_country;
	private static String session_country_name;
	private static String session_city;
	private static String session_city_name;
	private static String session_checked;
	private static String session_channel;
	private static String session_category;
	private static String session_category_name;
    
    
    
    public ImageLoader imageLoader; 
    
    private String idtransaksi;
	int phonecode =1;
 // Session Manager Class
 	SessionManager session;
 	LazyAdapter adapter;
 	ArrayList<HashMap<String, String>> menuItems;
 	ProgressDialog pDialog;
 	HashMap<String, String> map = new HashMap<String, String>();
 	
 	ArrayList<HashMap<String, String>> diskonba_list = new ArrayList<HashMap<String, String>>();
 	
 	//ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
 	
 	//slide menu
 	private LinearLayout slidingPanel;
 	private boolean isExpanded;
 	private DisplayMetrics metrics;
 	private RelativeLayout headerPanel;
 	private int panelWidth;
 	private int panelWidth1;
 	
 	private PullToRefreshListView mPullRefreshListView;
	ListView actualListView;
	

 	private String sta="";
 	private String id_;
 	ArrayList nameValuePairs;
	String result = null;
	InputStream is = null;
	StringBuilder sb=null;
	ImageLoader imgLoader;
	String tanggal1,tanggal2;
 	private ImageView menuViewButton,menuRightButton;
 	
 	FrameLayout.LayoutParams menuPanelParameters;
 	FrameLayout.LayoutParams slidingPanelParameters;
 	LinearLayout.LayoutParams headerPanelParameters;
 	LinearLayout.LayoutParams listViewParameters;
 	

 	private CharSequence[] value={"Bandung", "Jakarta"};
	
 	private EditText txt_city;
 	private TextView txt_search;
	private Button send;
	private Button cancel;

 	private Spinner spinnerFood;

	private int count;
	private String json; 
	private JSONObject jsonobject;
	public String code;
	public String msg;
	
	private ArrayList<City_Array> citylist;
	final List<String> list = new ArrayList<String>();
	private SlidingMenu sm;
	 
	public Search() {
		super(R.string.baru); 
	}


	@Override
	public void onBackPressed() { 
		Search.this.finish();
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        deklarasi_refresh();
        
        fungsi_menu();  
		session();	

		categorylist = new ArrayList<Category_Array>();
		txt_search=(EditText)findViewById(R.id.txt_search);    
		send=(Button)findViewById(R.id.send);     
        spinnerFood = (Spinner) findViewById(R.id.spinFood); 
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables); 
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		new loadDataCategory().execute();
		         
		aksi_klik();
         
		txt_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		    @Override
		    public void onFocusChange(View v, boolean hasFocus) {
		        if (!hasFocus) {
		            hideKeyboard(v);
		        }
		    }
		});
    }
	
	 public void hideKeyboard(View view) {
	        InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
	        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
	    }
	 
	public void aksi_klik(){
		
		send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				hideKeyboard(v);
				new loadListView().execute();
				 
			}
		});

		spinnerFood.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				//Toast.makeText(getBaseContext(), list.get(arg2).toString(),Toast.LENGTH_SHORT).show();
				 
				
				//System.out.println("print array list");
				String selec = spinnerFood.getSelectedItem().toString();
		
				Boolean exist = false;
				for(int i = 0; i < categorylist.size(); i++) 
				{
					
					String select_array = categorylist.get(i).getcategoryName().toString();
					if(select_array.equalsIgnoreCase(selec)){
						//System.out.println((categorylist.get(i).getcategoryName()).toString());
						//System.out.println((categorylist.get(i).getcategoryId()).toString());
						
						phonecode = Integer.parseInt(categorylist.get(i).getcategoryId().toString());
						//System.out.println("id category");
						//System.out.println(phonecode);
						
						exist=true;
			            break;
        			}
					
				} 
				
				 
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		}); 
         
		actualListView.setOnItemClickListener(new OnItemClickListener() { 
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
							// getting values from selected ListItem
				String list_id = ((TextView) view.findViewById(R.id.txt_voucher_id))
						.getText().toString();
	
				//System.out.println("masuk klik");
				//System.out.println(list_id);
				// Starting new intent
				Intent in = new Intent(Search.this,
						List_Data_Detail.class);
				in.putExtra(KEY_VOUCHER_ID, list_id);
				startActivity(in);
			}
		});  
	}
	
	
	public void deklarasi_refresh(){
		//loading
		mPullRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_list_search);

		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
 
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); 
				new loadMoreListView().execute();
			}
		}); 
  
		mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() { 
			@Override
			public void onLastItemVisible() {
				//Toast.makeText(FragmentSenin.this.getActivity(), "End of List!", Toast.LENGTH_SHORT).show();
			}
		});
			
		actualListView = mPullRefreshListView.getRefreshableView();
 
		registerForContextMenu(actualListView);
		
		
		//sound
		/*
		SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(FragmentSenin.this.getActivity());
		soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
		soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
		soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);
		mPullRefreshListView.setOnPullEventListener(soundListener);
		*/
		
		//variasi
		mPullRefreshListView.setMode(mPullRefreshListView.getMode() == Mode.BOTH ? Mode.PULL_FROM_START: Mode.BOTH);
		//mPullRefreshListView.setRefreshing(false);
		//mPullRefreshListView.setScrollingWhileRefreshingEnabled(!mPullRefreshListView.isScrollingWhileRefreshingEnabled());
		//mPullRefreshListView.demo();		
	}
	
	public void fungsi_menu(){
		
		setSlidingActionBarEnabled(true);
		 
        sm = getSlidingMenu();
		 
		LinearLayout header_vertical_divider_1 = (LinearLayout) findViewById(R.id.header_vertical_divider_1);
		LinearLayout header_vertical_divider_2 = (LinearLayout) findViewById(R.id.header_vertical_divider_2);
		ImageView diskonion_iconmenu = (ImageView) findViewById(R.id.diskonion_iconmenu);
		ImageView diskonion_iconhome = (ImageView) findViewById(R.id.diskonion_iconhome);
		ImageView diskonion_iconsearch = (ImageView) findViewById(R.id.diskonion_iconsearch);
		ImageView diskonion_iconcategory = (ImageView) findViewById(R.id.diskonion_iconcategory);
		
		
		
		diskonion_iconmenu.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showMenu(); 
			}
		}); 
		
		diskonion_iconhome.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Home.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconsearch.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Search.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconcategory.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showSecondaryMenu(); 
			}
		});
 		
	}
	
	
	public void session(){
		
		session = new SessionManager(getApplicationContext());
	    
	    HashMap<String, String> user = session.getUserDetails();
	     
	    // name
	    SessionManager session;
        session = new SessionManager(getApplicationContext());
         
        session_userid = user.get(SessionManager.id_users);
	    session_username = user.get(SessionManager.username);
	    session_password = user.get(SessionManager.password);
	    session_email = user.get(SessionManager.email);
	    session_country = user.get(SessionManager.country);
	    session_country_name = user.get(SessionManager.country_name);
	    session_city = user.get(SessionManager.city);
	    session_city_name = user.get(SessionManager.city_name);
	    session_checked = user.get(SessionManager.checked);
	    session_channel = user.get(SessionManager.channel);
	    session_category = "";
	    session_category_name = "";
	}
	
	  
	@SuppressLint("NewApi")
	private class loadDataCategory extends AsyncTask<Void, Void, Void>  {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Search.this);
			pDialog.setMessage("Getting data...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		protected Void doInBackground(Void... unused) {
		  
	    	Global.URL = Global.link_category_all;
			////System.out.println(Global.URL);  
			Global.URL = Global.URL.replace(" ", "%20");
			
			code="99";
			msg="Not connected to server";
			////System.out.println("Mulai do in background");
 
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				System.out.println("catch code msg");
				System.out.println(e);
				pDialog.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					System.out.println("catch 1");
					System.out.println(e);

					pDialog.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
		  
			return null;
		}
		
		
		protected void onPostExecute(Void unused) {
			 
			////System.out.println("onpostexecute"); 
			count = 0;  
			result = json;
			 

			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{  
				try{
					
			      	JSONArray jArray = new JSONArray(result);
			      	JSONObject json_data=null; 
			      	//System.out.println("array length");
			      	//System.out.println(jArray.length());
			      	
			      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i);  
						xml_programs_cat = json_data.getString(KEY_CATEGORY);  
						xml_programs_cat_id = json_data.getString(KEY_CATEGORY_ID);   
						//System.out.println(xml_programs_cat);  
						//System.out.println(xml_programs_cat_id);   
						//adapter.add(new SampleItem2(xml_countries_id, xml_countries_code, xml_countries_name));
						
						Category_Array cat = new Category_Array(xml_programs_cat_id,xml_programs_cat);
						categorylist.add(cat);  
						  
			      	} 
			      	
				}catch(JSONException e1){ 
					System.out.println("catch 2");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					System.out.println("catch 3");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				} 
			}
			if (pDialog.isShowing())
				pDialog.dismiss();
			populateSpinner();
			 
		 
		}
		 
	}
	
	private void populateSpinner() {
		List<String> lables = new ArrayList<String>(); 
		 

		for (int i = 0; i < categorylist.size(); i++) {
			lables.add(categorylist.get(i).getcategoryName());
		}

		 
		
		// Creating adapter for spinner
		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, lables);
		
		 
		// Drop down layout style - list view with radio button
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		 
		// attaching data adapter to spinner
		spinnerFood.setAdapter(spinnerAdapter); 
	}
	
	
	@SuppressLint("NewApi")
	private class loadListView extends AsyncTask<Void, Void, Void>  {

		@Override
		protected void onPreExecute() {
			 
		 
			
			pDialog = new ProgressDialog(
					Search.this);
			pDialog.setMessage("Retrieve Data, Please wait...");
			pDialog.setIndeterminate(true);
			pDialog.setCancelable(true);
			pDialog.show();
			 
			
			//counter
			/*
			new Thread(new Runnable() {
	        	@Override
	        	public void run() {
	        		count=30;
	        		try {
	        			while (count >= 0) {
	        				Thread.sleep(1000);
	        				//System.out.println("count "+count); 
	        				handle.sendMessage(handle.obtainMessage());
	        				count--;
	        				if (count <= 1) {
	        					progressDoalog.dismiss();
	        					//String mess = "waktu habis";
	        					//Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_SHORT).show();
	        				}
	        			} 
	        		} 
	        		catch (Exception e) {
	        			e.printStackTrace();
	        			//System.out.println("catch (Exception e) run : "+e);
	        		}
	        	}
	        }).start();
	        */
		}

		protected Void doInBackground(Void... unused) {
		 
			String result = null;
			InputStream is = null;
			StringBuilder sb=null; 

			ArrayList nameValuePairs = new ArrayList();
			
			
	    	Global.URL = Global.link_search + session_city + "&page=" + current_page+ "&category=" + phonecode + "&users=" + session_userid+ "&search=" + txt_search.getText().toString();
			System.out.println(Global.URL); 
	      
			// Next page request

			Global.URL = Global.URL.replace(" ", "%20");
			
			code="99";
			msg="Not connected to server";
			//System.out.println("Mulai do in background");
 
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				System.out.println("catch code msg");
				System.out.println(e);
				pDialog.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					System.out.println("catch 1");
					System.out.println(e);

					pDialog.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
		  
			return null;
		}
		
		
		protected void onPostExecute(Void unused) {
			 
			System.out.println("onpostexecute"); 
			count = 0; 
			//progressDoalog.dismiss(); 
			result = json;

			//System.out.println(diskonba_list.size());
			diskonba_list.clear();
			System.out.println("clear");
			//System.out.println(diskonba_list.size());

			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{ 
				try{
			      	JSONArray jArray = new JSONArray(result);
			      	JSONObject json_data=null;
	
			      	System.out.println("array length");
			      	System.out.println(jArray.length());
			      	
			      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i); 
						
						xml_voucher_id = json_data.getString(KEY_VOUCHER_ID);
						xml_voucher_name = json_data.getString(KEY_VOUCHER_NAME);
						//xml_voucher_total = json_data.getString(KEY_VOUCHER_TOTAL);
						//xml_voucher_tersedia = json_data.getString(KEY_VOUCHER_TERSEDIA);
						xml_voucher_detail = json_data.getString(KEY_VOUCHER_DETAIL);
						xml_merchant_id = json_data.getString(KEY_MERCHANT_ID);
						xml_merchant_category = json_data.getString(KEY_MERCHANT_CATEGORY);
						xml_merchant_name = json_data.getString(KEY_MERCHANT_NAME);
						xml_merchant_photo = json_data.getString(KEY_MERCHANT_PHOTO);
						xml_channel_name = "Channel : " + json_data.getString(KEY_CHANNEL_NAME);
						 
						System.out.println(xml_voucher_id);
						System.out.println(xml_voucher_name);
						////System.out.println("Total - " + xml_voucher_total);
						////System.out.println("Tersedia - " + xml_voucher_tersedia);
						//System.out.println(xml_voucher_detail); 
						//System.out.println(xml_merchant_id);
						//System.out.println(xml_merchant_category);
						//System.out.println(xml_merchant_name);
						//System.out.println(xml_channel_name);
						//System.out.println(Global.path + xml_merchant_photo);
						 
						
						HashMap<String, String> map = new HashMap<String, String>();
						//Element e = (Element) nl.item(i);
						// adding each child node to HashMap key => value
						map.put(KEY_VOUCHER_ID, xml_voucher_id);
						map.put(KEY_VOUCHER_DETAIL, xml_voucher_detail);
						map.put(KEY_MERCHANT_NAME, xml_merchant_name);
						map.put(KEY_CHANNEL_NAME, xml_channel_name);
						map.put(KEY_VOUCHER_NAME, xml_voucher_name); 
						map.put(KEY_MERCHANT_CATEGORY, xml_merchant_category); 
						//map.put(KEY_VOUCHER_TERSEDIA,  xml_voucher_tersedia + " Point"); 
						map.put(KEY_MERCHANT_PHOTO, Global.path + xml_merchant_photo);
	
						// adding HashList to ArrayList
						diskonba_list.add(map);
							
				      	}
			      	
				}catch(JSONException e1){ 
					System.out.println("catch 2");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					System.out.println("catch 3");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				} 
			} 
			
			 
			adapter = new LazyAdapter(Search.this, diskonba_list); 

			actualListView.setAdapter(null);
			actualListView.setAdapter(adapter);
			
			pDialog.dismiss();
		}
	}
 
	 
	@SuppressLint("NewApi")
	private class loadMoreListView extends AsyncTask<Void, Void, Void>  {

		@Override
		protected void onPreExecute() {
			/*
			pDialog = new ProgressDialog(
					FragmentSenin.this.getActivity());
			pDialog.setMessage("Retrieve Data, Please wait...");
			pDialog.setIndeterminate(true);
			pDialog.setCancelable(true);
			pDialog.show();
			*/
			
			//counter
			/*
			new Thread(new Runnable() {
	        	@Override
	        	public void run() {
	        		count=30;
	        		try {
	        			while (count >= 0) {
	        				Thread.sleep(1000);
	        				//System.out.println("count "+count); 
	        				handle.sendMessage(handle.obtainMessage());
	        				count--;
	        				if (count <= 1) {
	        					progressDoalog.dismiss();
	        					//String mess = "waktu habis";
	        					//Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_SHORT).show();
	        				}
	        			} 
	        		} 
	        		catch (Exception e) {
	        			e.printStackTrace();
	        			//System.out.println("catch (Exception e) run : "+e);
	        		}
	        	}
	        }).start();
	        */
		}

		protected Void doInBackground(Void... unused) {
			
			current_page += 1;
			String result = null;
			InputStream is = null;
			StringBuilder sb=null; 

			ArrayList nameValuePairs = new ArrayList();
			
			Global.URL = Global.link_search + session_city + "&page=" + current_page+ "&category=" + phonecode + "&users=" + session_userid+ "&search=" + txt_search.getText().toString();
			//System.out.println(Global.URL); 
	      
			
			code="99";
			msg="Not connected to server";
			//System.out.println("Mulai do in background");
 
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				System.out.println("catch code msg");
				System.out.println(e);
				pDialog.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					System.out.println("catch 1");
					System.out.println(e);

					pDialog.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
		  
			return null;
		}
		
		
		protected void onPostExecute(Void unused) {
			 
			//System.out.println("onpostexecute"); 
			count = 0; 
			//progressDoalog.dismiss(); 
			result = json;

			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{
				try{
			      	JSONArray jArray = new JSONArray(result);
			      	JSONObject json_data=null;
	
			      	//System.out.println("array length");
			      	//System.out.println(jArray.length());
			      	
			      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i); 
						
						xml_voucher_id = json_data.getString(KEY_VOUCHER_ID);
						xml_voucher_name = json_data.getString(KEY_VOUCHER_NAME);
						//xml_voucher_total = json_data.getString(KEY_VOUCHER_TOTAL);
						//xml_voucher_tersedia = json_data.getString(KEY_VOUCHER_TERSEDIA);
						xml_voucher_detail = json_data.getString(KEY_VOUCHER_DETAIL);
						xml_merchant_id = json_data.getString(KEY_MERCHANT_ID);
						xml_merchant_category = json_data.getString(KEY_MERCHANT_CATEGORY);
						xml_merchant_name = json_data.getString(KEY_MERCHANT_NAME);
						xml_merchant_photo = json_data.getString(KEY_MERCHANT_PHOTO);
						xml_channel_name = "Channel : " + json_data.getString(KEY_CHANNEL_NAME);
						 
						//System.out.println(xml_voucher_id);
						//System.out.println(xml_voucher_name);
						////System.out.println("Total - " + xml_voucher_total);
						////System.out.println("Tersedia - " + xml_voucher_tersedia);
						//System.out.println(xml_voucher_detail); 
						//System.out.println(xml_merchant_id);
						//System.out.println(xml_merchant_category);
						//System.out.println(xml_merchant_name);
						//System.out.println(xml_channel_name);
						//System.out.println(Global.path + xml_merchant_photo);
						 
						
						HashMap<String, String> map = new HashMap<String, String>();
						//Element e = (Element) nl.item(i);
						// adding each child node to HashMap key => value
						map.put(KEY_VOUCHER_ID, xml_voucher_id);
						map.put(KEY_VOUCHER_DETAIL, xml_voucher_detail);
						map.put(KEY_MERCHANT_NAME, xml_merchant_name);
						map.put(KEY_CHANNEL_NAME, xml_channel_name);
						map.put(KEY_VOUCHER_NAME, xml_voucher_name); 
						map.put(KEY_MERCHANT_CATEGORY, xml_merchant_category); 
						//map.put(KEY_VOUCHER_TERSEDIA,  xml_voucher_tersedia + " Point"); 
						map.put(KEY_MERCHANT_PHOTO, Global.path + xml_merchant_photo);
	
						// adding HashList to ArrayList
							diskonba_list.add(map);
						}
			      	
				}catch(JSONException e1){ 
					System.out.println("catch 2");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					System.out.println("catch 3");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				} 
			}
				 				
			 
		 
			
			int currentPosition = actualListView.getFirstVisiblePosition();
			
			//System.out.println("getFirstVisiblePosition " + actualListView.getFirstVisiblePosition());
			//System.out.println("getFooterViewsCount " + actualListView.getFooterViewsCount());
			//System.out.println("getHeaderViewsCount " + actualListView.getHeaderViewsCount());
			//System.out.println("getLastVisiblePosition " + actualListView.getLastVisiblePosition());
			
			adapter = new LazyAdapter(Search.this, diskonba_list); 
			actualListView.setAdapter(adapter);
      	
			// Setting new scroll position
			//System.out.println("current" + currentPosition + 1);
			actualListView.setSelectionFromTop(currentPosition + 1, 0); 
			mPullRefreshListView.onRefreshComplete();	 
			
		}
	} 
	
	
}
